<?php
defined('ACL_SESSION_KEY') or define('ACL_SESSION_KEY', Q::ini('acl_session_key'));
class Helper_RBAC
{
    static function change($name, $data, $roles)
    {
        //var_dump($name); exit;
        if(is_string($roles))
        {
            $roles = Q::normalize($roles);
        }
        $data['roles'] = implode(',', $roles);
        $_SESSION[ACL_SESSION_KEY][$name] = $data;
    }

    static function get($name)
    {
        static $user = array();

        $user_id = isset($_SESSION[ACL_SESSION_KEY][$name]['id'])
        ? $_SESSION[ACL_SESSION_KEY][$name]['id']
        : 0;
        $cache_id = "{$name}-{$user_id}";

        if(! isset($user[$cache_id]))
        {
            $user[$cache_id] = QDB_ActiveRecord_Meta::instance($name)
            ->findByArgs()
            ->getById($user_id);
        }
//        dump($user);
        return $user[$cache_id];
    }

    static function isLogined($name)
    {
        return self::get($name)->id > 0;
    }

    static function roles($name = null)
    {
        if(! empty($name))
        {
            return empty($_SESSION[ACL_SESSION_KEY][$name]['roles'])
            ? array()
            : Q::normalize($_SESSION[ACL_SESSION_KEY][$name]['roles']);
        }
        $roles = array();
        if(empty($_SESSION[ACL_SESSION_KEY]))
        {
            return $roles;
        }
        foreach($_SESSION[ACL_SESSION_KEY] as $key => $item)
        {
            $roles = array_merge($roles, Q::normalize($item['roles']));
        }
        return array_unique($roles);
    }

    static function chkroles($myRole, $name = null) {
        if(!$name) $name = 'user';
        $roles = self::roles($name);
        if(is_array($myRole)) {
            foreach($myRole as $role) {
                if(in_array($myRole, $roles)) {
                    return true;
                }
            }
        }
        else {
            return in_array($myRole, $roles);
        }
        return false;
    }

    static function clean($name)
    {
        unset( $_SESSION[ACL_SESSION_KEY][$name] );
    }

    static function cleanAll()
    {
        unset( $_SESSION[ACL_SESSION_KEY] );
    }
}